//
//  KRBurglarizedVC.m
//  KEREN
//
//  Created by MW on 2023/4/21.
//

#import "KRBurglarizedVC.h"
#import "KRSettingCell.h"
#import "BurglarHistoryVC.h"
#import "GaragelistViewController.h"
#import "KRSetBurglarizePointVC.h"
#import "BurglarModel.h"
@interface KRBurglarizedVC ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, copy) NSString *currentType;
@property (nonatomic, strong) DeviceInfo *deviceInfo;
@property (nonatomic, strong) NSString *addr;
@property (nonatomic, strong) NSString *deteStr;
@property (nonatomic, strong) UIButton *confirm;
@property (nonatomic, strong) BurglarModel *model;
@property (nonatomic, strong) UILabel *tipsLbl;
@property (nonatomic, assign) BOOL isBurglarized;

@end

@implementation KRBurglarizedVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"上报历史" navColorIswhite:YES withTitle:@"失窃上报"];
    WEAKSELF
    self.rightClickBlock = ^(void){
        BurglarHistoryVC *vc = [[BurglarHistoryVC alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    _titleArr = @[@"失窃上报类型",@"失窃车辆",@"失窃时间",@"失窃地点",@"车主电话"];
    self.currentType = @"车辆失窃";
    _addr = GDADDRESS;
    _deteStr = [[DeteManager shareInstance] getTodayStr];
    for (DeviceInfo *device in [UserInfoManager sharedInstance].deviceInfoList) {
        if(device.is_manager){
            _deviceInfo = device;
            break;
        }
    }    
    [self tableView];
    
    _confirm = [UIButton setButtonWithTitle:@"确认上报" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
    [self.view addSubview:_confirm];
    
    [_confirm mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
        make.bottom.offset(-BottomSpance_height);
    }];
    [_confirm addTarget:self action:@selector(confirmClick) forControlEvents:UIControlEventTouchUpInside];
    
    _tipsLbl = [UILabel setLblText:@"失窃上报后将自动锁定车辆" font:Font(14) withColor:Color_86898E inSubView:self.view];
    [_tipsLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_confirm.mas_top).offset(-12);
        make.centerX.equalTo(self.view);
    }];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //注册、接收通知
    [center addObserver:self selector:@selector(chooseDevice:) name:CHOOSEDEVICE object:nil];
    [center addObserver:self selector:@selector(choosePoint:) name:CHOOSEPOINT object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getLoseDetail];
}

- (void)getLoseDetail{
    WEAKSELF
    [NetworkingTool POST:@"/v1/lose/list" parameters:@{@"ebike_id":@(_deviceInfo.Id),@"status":@(0)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if([response[@"data"][@"list"] isKindOfClass:[NSArray class]]){
                NSArray *dataArr = response[@"data"][@"list"];
                if(dataArr.count > 0){
                    weakSelf.isBurglarized = YES;
                    [weakSelf.confirm setTitle:@"解除失窃" forState:UIControlStateNormal];
                    weakSelf.tipsLbl.text = @"解除失窃后将自动解锁车辆";
                }else{
                    weakSelf.isBurglarized = NO;
                    [weakSelf.confirm setTitle:@"立即上报" forState:UIControlStateNormal];
                    weakSelf.tipsLbl.text = @"失窃上报后将自动锁定车辆";
                }
            }
        }else{
            weakSelf.isBurglarized = NO;
            [weakSelf.confirm setTitle:@"立即上报" forState:UIControlStateNormal];
            weakSelf.tipsLbl.text = @"失窃上报后将自动锁定车辆";
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)confirmClick{
    _confirm.enabled = NO;
    WEAKSELF
    if(_isBurglarized){
        [[KRAlartManager shareInstance] showTipsAlertWithTitle:@"确定解除失窃上报吗？" decTitle:@"解除失窃后将自动解锁车辆" cancleBtnText:@"取消" andOkBtnText:@"确认" sucessBlock:^(BOOL isSucess) {
            if(isSucess){
                [NetworkingTool POST:@"/v1/app/lose/unlock" parameters:@{@"ebike_id":@(weakSelf.deviceInfo.Id)} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
                    weakSelf.confirm.enabled = YES;
                    if([response[@"code"] intValue] == 0){
                        BurglarHistoryVC *vc = [[BurglarHistoryVC alloc] init];
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    }
                } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
                    weakSelf.confirm.enabled = YES;
                }];
            }else{
                weakSelf.confirm.enabled = YES;
            }
        }];
    }else{
        NSString *addrStr = @"";
        if(![_addr isEqualToString:@"未填写"]){
            addrStr = _addr;
        }
        NSInteger type = 1;
        if(![_currentType isEqualToString:@"车辆失窃"]){
            type = 2;
        }
        if(addrStr.length < 1){
            [[KRAlartManager shareInstance] showErrorAlert:@"地址不可为空"];
            _confirm.enabled = YES;
            return;
        }
        NSDictionary *dict = @{@"ebike_id":@(_deviceInfo.Id),@"lose_time":@([[DeteManager shareInstance] getDay:_deteStr]),@"addr":addrStr,@"desc":@"",@"lose_type":@(type)};
        [[KRAlartManager shareInstance] showTipsAlertWithTitle:@"确定提交失窃上报吗？" decTitle:@"失窃上报后将自动锁定车辆" cancleBtnText:@"取消" andOkBtnText:@"确认" sucessBlock:^(BOOL isSucess) {
            if(isSucess){
                [NetworkingTool POST:@"/v1/lose/create" parameters:dict isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
                    weakSelf.confirm.enabled = YES;
                    if([response[@"code"] intValue] == 0){
                        BurglarHistoryVC *vc = [[BurglarHistoryVC alloc] init];
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    }
                } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
                    weakSelf.confirm.enabled = YES;
                }];
            }else{
                weakSelf.confirm.enabled = YES;
            }
        }];
    }
}

- (void)chooseDevice:(NSNotification *)notifacation{
    _deviceInfo = notifacation.object;
    [self.tableView reloadData];
}
- (void)choosePoint:(NSNotification *)notifacation{
    _addr = notifacation.object;
    [self.tableView reloadData];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _titleArr.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KRSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRSettingCell"];
    cell.nameLbl.text = _titleArr[indexPath.row];
    cell.rightIcon.hidden = NO;
    cell.photoIcon.hidden = YES;
    cell.decLeftConstraint.constant = 14;
    if(indexPath.row == 0){
        cell.decLbl.text = self.currentType;
    }else if(indexPath.row == 1){
        cell.decLbl.text = _deviceInfo.name;
    }else if(indexPath.row == 2){
        cell.decLbl.text = _deteStr;
        cell.rightIcon.hidden = YES;
        cell.decLeftConstraint.constant = 0;
    }else if(indexPath.row == 3){
        cell.decLbl.text = _addr;
    }else{
        cell.decLbl.text = USERINFO.phone;
        cell.rightIcon.hidden = YES;
        cell.decLeftConstraint.constant = 0;
    }
    if(indexPath.row == _titleArr.count - 1){
        cell.lineView.hidden = YES;
    }else{
        cell.lineView.hidden = NO;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if(indexPath.row == 0){
        WEAKSELF
        [[KRAlartManager shareInstance]  showPickAlertView:@"失窃上报类型" withcurrentIndex:0 IscanChooseHistory:NO changeTitleBlock:^(NSString * _Nonnull title) {
            weakSelf.currentType = title;
            [weakSelf.tableView reloadData];
        }];
    }else if(indexPath.row == 1){
        GaragelistViewController *vc = [[GaragelistViewController alloc] init];
        [vc getDeviceList];
        vc.type = 1001;
        [self.navigationController pushViewController:vc animated:YES];
    }else if(indexPath.row == 2){

    }else if (indexPath.row == 3){
        KRSetBurglarizePointVC *vc = [[KRSetBurglarizePointVC alloc] init];
        vc.addr = _addr;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVTOP_Height, DEVICE_WIDTH, DEVICE_HEIGHT - NAVTOP_Height)];
        _tableView.backgroundColor = Main_BackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"KRSettingCell" bundle:nil] forCellReuseIdentifier:@"KRSettingCell"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}


@end
